<template>
  <view>
    <view class="page-content">
      <view class="page-by-nurse">
        <view class="by-nurse-list">
          <view
            class="by-nurse-item"
            v-for="item in state.addressList"
            :key="item.id"
            @click="curId = item.id"
          >
            <view class="by-nurse-item-left">
              <view class="by-nurse-item-icon">
                <uni-icons
                  v-if="item.id == curId"
                  type="checkbox-filled"
                  color="#4cd964"
                  size="24"
                ></uni-icons>
                <uni-icons
                  v-else
                  type="circle"
                  color="#4cd964"
                  size="24"
                ></uni-icons>
              </view>
              <view class="by-nurse-item-base">
                <view class="by-nurse-item-name-box">
                  <text class="by-nurse-item-name">{{
                    item.province + item.city + item.district
                  }}</text>
                  <!-- <up-tag size="mini" text="默认"></up-tag> -->
                </view>
                <view class="by-nurse-item-age">
                  {{ item.detailAddress }}
                </view>
              </view>
            </view>
            <view class="by-nurse-item-right">
              <up-icon
                name="edit-pen"
                color="#2979ff"
                size="24"
                @click="openCreate('修改', item)"
              ></up-icon>
              <up-icon
                @click="openDel(item)"
                name="trash"
                color="#ff0000"
                size="24"
              ></up-icon>
            </view>
          </view>
        </view>
      </view>
      <view
        class="empty-main"
        v-if="state.addressList.length == 0 && addressListHide"
      >
        <up-empty mode="order" icon="file-text" text="护理人地址为空">
        </up-empty>
      </view>
      <view class="footer-btn footer">
        <view class="footer-btn-main">
          <view class="custom-style">
            <up-button
              type="primary"
              shape="circle"
              text="新增"
              @click="openCreate('新增')"
            ></up-button>
          </view>
          <view class="custom-style">
            <up-button
              type="primary"
              shape="circle"
              text="确定"
              @click="openCreate('确定')"
            ></up-button>
          </view>
        </view>
      </view>
    </view>
    <up-popup :show="isHide" closeable mode="bottom" @close="close">
      <view class="create-edit-main">
        <view class="create-edit-title">{{ titleName }}</view>
        <view class="create-edit-form">
          <up-form
            labelPosition="top"
            labelWidth="auto"
            :model="state.model1"
            :rules="state.rules"
            ref="formRef"
          >
            <up-form-item
              label="所在城市"
              prop="userInfo.district"
              borderBottom
              @click="state.showSex = true"
            >
              <uni-data-picker
                v-model="state.province"
                placeholder="请选择地址"
                popup-title="请选择城市"
                :localdata="city"
                field="请选择城市"
                :step-searh="true"
                self-field="code"
                parent-field="parent_code"
                :map="{ text: 'name', value: 'name' }"
                @change="sexSelect"
              >
              </uni-data-picker>
            </up-form-item>
            <up-form-item
              label="详细地址"
              prop="userInfo.detailAddress"
              borderBottom
            >
              <up-textarea
                v-model="state.model1.userInfo.detailAddress"
                placeholder="请输入具体地址"
              ></up-textarea>
            </up-form-item>
          </up-form>
          <view class="submit-form footer">
            <view class="submit-form-btn">
              <up-button
                :loading="isLoading"
                type="primary"
                shape="circle"
                text="提交"
                @click="submitForm('提交')"
              ></up-button>
            </view>
          </view>
        </view>
      </view>
    </up-popup>
    <!-- <up-popup v-model:show="isDelShow" mode="center" :round="10">
    <view class="del-main">
      <view class="del-title">删除</view>
      <view class="tips">{{ content }}</view>
      <view class="del-main-btn">
        <up-button :plain="true" text="取消"></up-button>
        <up-button type="primary" text="确定"></up-button>
      </view>
    </view>
  </up-popup> -->
    <uni-popup ref="popupRef" type="dialog">
      <uni-popup-dialog
        mode="base"
        title="删除"
        content="删除后无法恢复？"
        :duration="2000"
        :before-close="true"
        @close="closeVs"
        @confirm="confirmVs"
      ></uni-popup-dialog>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { onReady } from "@dcloudio/uni-app";
import { city } from "@/utils/city-data";

import {
  GetAddress,
  AddressCreate,
  AddressDelete,
  AddressUpdate,
} from "@/api/my.js";

const emits = defineEmits(["update:updateByNurseAddress"]);

let popupRef = ref(null);

/**
 * 点击取消按钮触发
 * @param {Object} done
 */
const closeVs = () => {
  // TODO 做一些其他的事情，before-close 为true的情况下，手动执行 close 才会关闭对话框
  // ...
  popupRef.value.close();
};
/**
 * 点击确认按钮触发
 * @param {Object} done
 * @param {Object} value
 */
const confirmVs = async (value) => {
  // 输入框的值
  let params = {
    id: deteleId.value,
  };
  try {
    let data = await AddressDelete(params);
    popupRef.value.close();
    GetAddressList();
  } catch (error) {
    popupRef.value.close();
  }
};

let isCurrent = ref(1);

let isHide = ref(false);
let titleName = ref("新增");
let timeShow = ref(false);
const close = () => {
  isHide.value = false;
  console.log("close");
};

const openTion = (item) => {
  uni.navigateTo({
    url: "/pages/mine/orderList/detail?types=" + item.id,
  });
};

// 新增
let curId = ref("");
const openCreate = (title, row) => {
  titleName.value = title;
  if (title == "确定") {
    if (!curId.value) {
      uni.showToast({
        title: "请选择地址",
        icon: "none",
      });
      return;
    }
    let item = state.addressList.find((o) => o.id == curId.value);
    console.log(item, "item");
    emits("update:updateByNurseAddress", item);
    return;
  }
  if (title == "修改") {
    state.province = `${row.district}`;
    state.model1.userInfo = JSON.parse(JSON.stringify(row));
  } else {
    state.province = "";
    state.model1.userInfo = {
      province: "",
      city: "",
      district: "",
      detailAddress: "",
    };
  }
  isHide.value = true;
};

// 使用 reactive 创建响应式状态
const state = reactive({
  province: "",
  showSex: false,
  addressList: [],
  model1: {
    userInfo: {
      province: "",
      city: "",
      district: "",
      detailAddress: "",
    },
  },
  actions: [{ name: "男" }, { name: "女" }, { name: "保密" }],
  rules: {
    "userInfo.district": {
      type: "string",
      required: true,
      message: "请选择城市",
      trigger: ["blur", "change"],
    },
    "userInfo.detailAddress": {
      type: "string",
      required: true,
      message: "请输入具体地址",
      trigger: ["blur", "change"],
    },
  },
  radio: "",
  switchVal: false,
});

// 使用 ref 创建响应式引用
const formRef = ref(null);

// 定义方法
function sexSelect(e) {
  console.log(e, "ww");
  if (e.detail.value.length) {
    state.model1.userInfo.province = e.detail.value[0].text;
    state.model1.userInfo.city = e.detail.value[1].text;
    state.model1.userInfo.district = e.detail.value[2].text;
  } else {
    state.model1.userInfo.province = "";
    state.model1.userInfo.city = "";
    state.model1.userInfo.district = "";
  }
  formRef.value.validateField("userInfo.district");
}

const selectTimer = (event) => {
  console.log(event, "$event");
  state.model1.userInfo.time = event;
  timeShow.value = true;
};

let isLoading = ref(false);
const submitForm = () => {
  let datares = {};
  formRef.value.validate().then(async (valid) => {
    try {
      isLoading.value = true;
      if (state.model1.userInfo.id) {
        datares = await AddressUpdate(state.model1.userInfo);
      } else {
        datares = await AddressCreate(state.model1.userInfo);
      }
      isHide.value = false;
      GetAddressList();
      isLoading.value = false;
    } catch (error) {
      isLoading.value = false;
    }
  });
};

let addressListHide = ref(false);
const GetAddressList = async () => {
  let { data } = await GetAddress();
  addressListHide.value = true;
  state.addressList = data;
};

let isDelShow = ref(false);
let title = ref("删除");
let content = ref("确认删除当前被保护人吗？");
let deteleId = ref("");
const openDel = (row) => {
  deteleId.value = row.id;
  popupRef.value.open();
};

onMounted(() => {
  GetAddressList();
});
</script>

<style scoped lang="scss">
.page-content {
  height: 40vh;
  padding: 20rpx 0 80rpx 0;
  box-sizing: border-box;
  background: #f2f2f2;
}
.by-nurse-item {
  padding: 20rpx;
  margin: 0 20rpx 20rpx 20rpx;
  background: #fff;
  border-radius: 16rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  .by-nurse-item-name-box {
    display: flex;
    align-items: center;
    .by-nurse-item-name {
      margin-right: 10px;
    }
  }
  .by-nurse-item-age {
    margin-top: 10rpx;
    font-size: 28rpx;
    color: #999;
  }
  .by-nurse-item-right {
    display: flex;
    justify-content: center;
  }
}
::v-deep .u-icon {
  margin-left: 10rpx;
}
::v-deep .u-tag {
  height: 24rpx !important;
  line-height: 24rpx !important;
  padding: 5rpx !important;
}
.create-edit-main {
  min-height: 60vh;
  .create-edit-title {
    text-align: center;
    line-height: 3;
    border-bottom: 1px solid #f2f2f2;
  }
}
.create-edit-form {
  padding: 0 20rpx;
}
.select-time-tips {
  color: #ccc;
}
.submit-form {
  position: fixed;
  left: 20rpx;
  right: 20rpx;
  bottom: 0;
}
.submit-form-btn,
.footer-btn-main {
  padding-bottom: 20rpx;
}
.footer-btn-main {
  display: flex;
}
.del-main {
  padding: 20rpx 60rpx;
  text-align: center;
  .del-title {
    padding: 20rpx;
    font-weight: bold;
    font-size: 36rpx;
  }
  .tips {
    color: #999;
  }
  .del-main-btn {
    display: flex;
    margin-top: 40rpx;
  }
}
.empty-main {
  margin-top: 10vh;
}
.custom-style {
  margin: 0 10rpx;
  width: calc(50% - 10rpx);
}
.by-nurse-item-left {
  display: flex;
  align-items: center;
  .by-nurse-item-icon {
    margin-right: 20rpx;
  }
}
</style>
